package com.example.nowcodercommunity.controller;

import com.example.nowcodercommunity.annotation.LoginRequire;
import com.example.nowcodercommunity.entity.User;
import com.example.nowcodercommunity.service.CommunityConstant;
import com.example.nowcodercommunity.service.FollowService;
import com.example.nowcodercommunity.service.LikeService;
import com.example.nowcodercommunity.service.UserService;
import com.example.nowcodercommunity.util.CommunityUtil;
import com.example.nowcodercommunity.util.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 关于用户功能相关的Controller
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domainPath;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;
    
    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    /**
     * 返回设置页
     * @return
     */
    @LoginRequire
    @RequestMapping(path = "/setting",method = RequestMethod.GET)
    public String getUserSettingPage(){
        return "/site/setting";
    }

    /**
     * 用户主页，允许查看他人主页
     * @param userId
     * @param model
     * @return
     */
    @LoginRequire
    @RequestMapping(path = "/profile/{userId}",method = RequestMethod.GET)
    public String getUserMainPage(@PathVariable(name = "userId") int userId,Model model){
        User user = userService.findUserById(userId);

        if(user==null){
            throw new RuntimeException("目标用户不存在！");
        }
        
        model.addAttribute("user", user);

        int userLikeCount = likeService.getUserLikeCount(userId);
        model.addAttribute("likeCount", userLikeCount);

        // 被关注数量
        long userFollowerCount = followService.getEntityFollowerCount(userId, CommunityConstant.ENTITY_TYPE_USER);
        model.addAttribute("followerCount", userFollowerCount);

        // 关注数量
        long userFolloweeCount = followService.getUserFolloweeCount(userId, CommunityConstant.ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", userFolloweeCount);

        // 浏览主页者是否已关注主页主人
        boolean hasFollowed = false;
        if(hostHolder.getUser()!=null){
            hasFollowed = followService.hasUserFollowedEntity(hostHolder.getUser().getId(), CommunityConstant.ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        return "/site/profile";
    }

    /**
     * 上传头像
     * @param headerImage
     * @param model
     * @return
     * @throws IOException
     */
    @LoginRequire
    @RequestMapping(path = "/upload",method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model) throws IOException {
        if(headerImage == null){
            model.addAttribute("error","您还没有选择图片!");
            return "/site/setting";
        }

        String fileName = headerImage.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if(StringUtils.isEmpty(suffix)){
            model.addAttribute("error","文件格式不正确！");
            return "site/setting";
        }

        fileName = CommunityUtil.generateUUID() + suffix;
        System.out.println(uploadPath);
        System.out.println(domainPath);

        File dest = new File(uploadPath + "/" + fileName);
        try {
            headerImage.transferTo(dest);
        }catch (IOException e){
            logger.error("上传文件失败：" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器发生异常！",e);
        }

        User user = hostHolder.getUser();
        String headerUrl = domainPath + contextPath + "/user/header/" + fileName;
        userService.updateUserHeader(user.getId(),headerUrl);

        return "redirect:/index";
    }

    /**
     * 获取头像
     * @param fileName
     * @param response
     */
    @RequestMapping(path = "/header/{fileName}",method = RequestMethod.GET)
    public void getHeader(@PathVariable(name = "fileName") String fileName, HttpServletResponse response){
        fileName = uploadPath + "/" + fileName;
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        response.setContentType("image/" + suffix);
        try{
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(fileName);
            byte[] buffer = new byte[1024];
            int b = 0;
            while((b=fis.read(buffer))!=-1){
                os.write(buffer,0,b);
            }
        }catch (IOException e){
            logger.error("读取头像失败：",e.getMessage());
        }
    }

    /**
     * 修改密码，暂未测试
     * @param model
     * @param oldPassword
     * @param newPassword
     * @param confirmPassword
     * @return
     */
    @LoginRequire
    @RequestMapping(path = "/updatePassword",method = RequestMethod.POST)
    public String updateUserPassword(Model model, String oldPassword, String newPassword, String confirmPassword){
        if(StringUtils.isEmpty(oldPassword)){
            model.addAttribute("oldPasswordMsg","旧密码不可为空！");
            return "site/setting";
        }
        if(StringUtils.isEmpty(newPassword)){
            model.addAttribute("newPasswordMsg","新密码不可为空！");
            return "site/setting";
        }
        if(StringUtils.isEmpty(confirmPassword)){
            model.addAttribute("confirmPasswordMsg","请重复输入密码以确认！");
            return "site/setting";
        }

        User user = hostHolder.getUser();
        if(!user.getPassword().equals(oldPassword)){
            model.addAttribute("oldPasswordMsg","密码错误！");
            return "site/setting";
        }
        if(!newPassword.equals(confirmPassword)){
            model.addAttribute("confirmPasswordMsg","两次密码不一致，请检查确认密码！");
            return "site/setting";
        }

        userService.updateUserPassword(user.getId(),newPassword);
        model.addAttribute("msg","您已成功修改密码，请重新登录！");
        model.addAttribute("target","/login");

        return "/site/operate-result";
    }
}
